package com.quyunshuo.module.home.activity.main

import android.annotation.SuppressLint
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import coil.load
import com.quyunshuo.module.home.R
import com.quyunshuo.module.home.room.entity.PoetEntity

class MusicAdapter(
    private val context: Context,
    private var musicList: List<PoetEntity>
) : RecyclerView.Adapter<MusicAdapter.ViewHolder>() {
    // 当前选中的位置
    var selectedPosition: Int = -1
        set(value) {
            if (field == value) return
            // 只刷新变化的项目
            val oldPosition = field
            field = value

            if (oldPosition != -1) notifyItemChanged(oldPosition)
            if (value != -1) notifyItemChanged(value)

        }

    var onItemClickListener: ((Int) -> Unit)? = null

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val albumArt: ImageView = itemView.findViewById(R.id.album_art)
        val title: TextView = itemView.findViewById(R.id.title)
        val artist: TextView = itemView.findViewById(R.id.artist)
        val duration: TextView = itemView.findViewById(R.id.duration)

        init {
            itemView.setOnClickListener {
                val position = adapterPosition
                if (position != RecyclerView.NO_POSITION) {
                    selectedPosition = position
                    onItemClickListener?.invoke(position)
                }
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_music, parent, false)
        return ViewHolder(view)
    }

    @SuppressLint("SuspiciousIndentation")
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val music = musicList[position]
        // 设置标题颜色
        if (position == selectedPosition) {
            // 选中状态 - 使用主题色
            holder.title.setTextColor(ContextCompat.getColor(context, R.color.base_colorAccent))
        } else {
            // 默认状态 - 使用黑色
            holder.title.setTextColor(ContextCompat.getColor(context, android.R.color.black))
        }
        holder.title.text = music.name
        holder.artist.text = music.intro
        holder.duration.text = music.style
        holder.albumArt.setImageResource(R.drawable.setting_icon)
    }

    override fun getItemCount(): Int = musicList.size

    fun updateList(newList: List<PoetEntity>) {
        musicList = newList
        notifyDataSetChanged()
    }


}